import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:frontend/models/briefItems.dart';
import 'package:frontend/models/order.dart';
import 'package:frontend/pages/ItemPage.dart';
import 'package:frontend/pages/addressPage.dart';
import 'package:frontend/pages/chattingIntroducePage.dart';
import 'package:frontend/pages/historyOrderPage.dart';
import 'package:frontend/pages/personalChattingPage.dart';
import 'package:frontend/pages/regOrLogPage.dart';
import 'package:frontend/pages/registerPage.dart';
import 'package:frontend/pages/storePage.dart';
import 'package:frontend/reqs/requests.dart';
import 'package:frontend/states/userState.dart';
import 'package:frontend/utils.dart';
import 'package:provider/provider.dart';

import '../models/global.dart';
import 'cartPage.dart';
import 'orderPage.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final TextEditingController _searchController =
      TextEditingController(text: '');
  bool _themeSwitch = false;

  @override
  Widget build(BuildContext context) {
    final drawerItems = ListView(
      children: [
        Consumer<UserState>(
          builder: (context, userState, child) {
            return UserAccountsDrawerHeader(
              accountName: userState.isLogin
                  ? Text(userState.user!.name)
                  : const Text("请登录"),
              accountEmail: null,
              currentAccountPicture: CircleAvatar(
                child: ClipOval(
                  clipper: MyClipper(70.0),
                  child: userState.isLogin
                      ? Image.memory(userState.user!.img)
                      : Image.asset('assets/img/shiroko.png'),
                ),
              ),
            );
          },
        ),
        ListTile(
          title: const Text(
            "聊天",
          ),
          leading: const Icon(Icons.comment),
          onTap: () {
            if (!Global.profile.isLogin) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('请先登录！'),
                ),
              );
            } else {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: ((context) => ChattingIntroducePage())));
            }
          },
        ),
        ListTile(
          title: const Text('购物车'),
          leading: const Icon(Icons.shopping_cart),
          onTap: () {
            if (!Global.profile.isLogin) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('请先登录'),
                ),
              );
            } else {
              Navigator.push(context,
                  MaterialPageRoute(builder: ((context) => CartPage())));
            }
          },
        ),
        ListTile(
          title: const Text('地址管理'),
          leading: const Icon(Icons.where_to_vote_outlined),
          onTap: () {
            if (!Global.profile.isLogin) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('请先登录'),
                ),
              );
            } else {
              Navigator.push(context,
                  MaterialPageRoute(builder: ((context) => AddressPage())));
            }
          },
        ),
        ListTile(
          title: const Text('历史订单'),
          leading: const Icon(Icons.text_snippet_outlined),
          onTap: () {
            if (!Global.profile.isLogin) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('请先登录'),
                ),
              );
            } else {
              Navigator.push(
                  context,
                  MaterialPageRoute(
                      builder: ((context) => HistoryOrderPage())));
            }
          },
        ),
        /*ListTile(
          title: const Text(
            "发布",
          ),
          leading: const Icon(Icons.publish),
          onTap: () {
            Navigator.pop(context);
          },
        ),*/
        ListTile(
          title: const Text(
            "我的店铺",
          ),
          leading: const Icon(Icons.store),
          onTap: () {
            if (!Global.profile.isLogin) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('请先登录！'),
                ),
              );
            } else {
              Navigator.push(context,
                  MaterialPageRoute(builder: ((context) => StorePage())));
            }
          },
        ),
        ListTile(
          title: const Text("登录/注册"),
          leading: const Icon(Icons.login),
          onTap: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (context) => const RegOrLogPage()));
          },
        ),
        ListTile(
          title: const Text("夜间主题"),
          leading: const Icon(Icons.light_mode_outlined),
          trailing: Switch(
            value: Provider.of<UserState>(context).isDark, //当前状态
            onChanged: (value) {
              //重新构建页面
              setState(() {
                Provider.of<UserState>(context, listen: false).isDark = value;
              });
            },
          ),
        ),

      ],
    );

    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: FutureBuilder<BriefItems>(
        future: /*mockSearchData(_searchController.text)*/ _searchController
                .text.isEmpty
            ? queryAllItems()
            : queryItemByKeywords(_searchController.text),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasError) {
              return Text(snapshot.error.toString());
              //return const Icon(Icons.error);
            } else {
              return GridView.count(
                  restorationId: 'grid_view_demo_grid_offset',
                  crossAxisCount: 4,
                  mainAxisSpacing: 8,
                  crossAxisSpacing: 8,
                  padding: const EdgeInsets.all(8),
                  childAspectRatio: 1,
                  children: snapshot.data!.items
                      .map((e) => ItemCard(
                            itemId: e.id,
                            image: Image.memory(e.img),
                            title: e.name,
                            price: e.price,
                            //itemId: e.id,
                          ))
                      .toList());
            }
          } else {
            // 请求未结束，显示loading
            return CircularProgressIndicator();
          }
        },
      ),
      /*floatingActionButton: FloatingActionButton(
        onPressed: () {},
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
      // This trailing comma makes auto-formatting nicer for build methods.
      floatingActionButtonLocation: FloatingActionButtonLocation.endDocked,*/
      drawer: Drawer(
        child: drawerItems,
      ),
      bottomNavigationBar: BottomAppBar(
          shape: const CircularNotchedRectangle(),
          child: Row(
            children: [
              IconButton(
                icon: const Icon(Icons.search),
                onPressed: () {
                  setState(() {
                    // just call it to rebuild ui
                  });
                },
              ),
              Container(
                  width: 150,
                  child: TextField(
                    controller: _searchController,
                    decoration: InputDecoration(
                      border: OutlineInputBorder(),
                      hintText: '输入搜索内容',
                    ),
                  )),
            ],
          )),
    );
  }
}

class ItemCard extends StatelessWidget {
  final int itemId;
  final Image image;
  final String title;
  final int price;

  const ItemCard(
      {super.key,
      required this.itemId,
      required this.image,
      required this.title,
      required this.price});

  @override
  Widget build(BuildContext context) {
    return GridTile(
      footer: Material(
        color: Colors.transparent,
        shape: const RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(4)),
        ),
        clipBehavior: Clip.antiAlias,
        child: GridTileBar(
          backgroundColor: Colors.black45,
          title: Text('$title ￥$price'),
          subtitle: TextButton(
              onPressed: () {
                print(itemId);
                Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (context) => ItemPage(itemId: itemId)));
              },
              child: Text('详情')),
        ),
      ),
      child: image,
    );
  }
}
